package com.mmall.controller.common.Interceptor;

import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.util.CookieUtil;
import com.mmall.util.JsonUtil;
import com.mmall.util.RedisShardedPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Handler;

@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object O) throws Exception {
        log.info("preHandle");

        //请求中Controller中的方法名
        HandlerMethod handlerMethod = (HandlerMethod) O;

        //解析 HandlerMethod
        String methodName =  handlerMethod.getMethod().getName();
        String className = handlerMethod.getBean().getClass().getSimpleName();

        //解析参数，具体的参数key以及value是什么，打印日志
        StringBuffer requestParamBuffer = new StringBuffer();
        Map paraMap = httpServletRequest.getParameterMap();

        Iterator iterator = paraMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();

            String mapValue = StringUtils.EMPTY;

            //request这个参数的map 里面value返回的是以个string【】
            Object value =  entry.getValue();
            if (value instanceof  String[]){
                String[] strs = (String[]) value;
                mapValue = Arrays.toString(strs);
            }
            requestParamBuffer.append(key).append("=").append(mapValue);
        }

        if (StringUtils.equals(className,"UserManageController") && StringUtils.equals(methodName,"login")){
            log.info("权限拦截器拦截到请求，className{}，methodName:{}",className,methodName);
            //如果拦截到登陆请求，不打印参数，
            return true;
        }

        User user = null;
        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if (StringUtils.isNotEmpty(loginToken)){
            String userJsonStr = RedisShardedPoolUtil.get(loginToken);
            user = JsonUtil.string20bj(userJsonStr,User.class);

        }

        if (user == null || (user.getRole().intValue() != Const.Role.ROLE_ADMIN)){
            //返回false 即不会调用Controller
            httpServletResponse.reset();  //这里要添加reset，否则报异常  getWriter() has already been called for this response.
            httpServletResponse.setCharacterEncoding("UTF-8"); //设置编码 否则乱码
            httpServletResponse.setContentType("application/json;charset=UTF-8"); //这里用

            PrintWriter out = httpServletResponse.getWriter();

            //上传由于富文本要求 需判断
            if (user == null){
                if (StringUtils.equals(className,"ProductManagerController") && StringUtils.equals(methodName,"richtext_img_upload")){
                    Map resultMap = Maps.newHashMap();
                    resultMap.put("success",false);
                    resultMap.put("msg","用户未登录，无法获取当前用户信息");
                    out.print(JsonUtil.obj2String(resultMap));
                }else {
                    out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("拦截器拦截，用户未登陆")));
                }
            }else{
                if (StringUtils.equals(className,"ProductManagerController") && StringUtils.equals(methodName,"richtext_img_upload")){
                    Map resultMap = Maps.newHashMap();
                    resultMap.put("success",false);
                    resultMap.put("msg","拦截器拦截，用户无权限操作");
                    out.print(JsonUtil.obj2String(resultMap));
                }else {
                    out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("拦截器拦截，用户无权限操作")));
                }
            }
            out.flush();
            out.close();//这里要关闭

            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("afterCompletion");
    }
}
